import { getClusterTaskPage, getClusterTaskResult } from '@/api/develop/clusterTask'
import type Node from 'element-plus/es/components/tree/src/model/node'

interface Tree {
  name: string
  leaf?: boolean
}

const message = useMessage() // 消息弹窗

export function useSelectData() {
  const taskList = ref([])

  const props = {
    label: 'name',
    isLeaf: 'leaf'
  }

  function handleLoad(node: Node, resolve: (data: Tree[]) => void, reject: () => void) {
    if (node.level === 0) {
      return loadNode(resolve, reject)
    }
    if (node.level > 1) return resolve([])

    return loadNode(resolve, reject, node)
  }

  async function loadNode(resolve: (data: Tree[]) => void, reject: () => void, node?: Node) {
    if (!node) {
      try {
        const { data } = await getClusterTaskPage({
          page: 1,
          pageSize: 999999
        })
        const tree_ = data.map((item) => ({
          name: item.name,
          id: item.id
        }))
        taskList.value = tree_
        return resolve(tree_)
      } catch (error) {
        return reject()
      }
    } else {
      try {
        const res = await getClusterTaskResult(node.data.id)
        if (!res || res.length === 0) {
          node.data.disabled = true // 设置禁用
          message.info('该任务下没有聚类结果')
        }
        const tree_ = res.map((item) => ({
          name: item.name,
          id: item.id,
          leaf: true
        }))
        return resolve(tree_)
      } catch (error) {
        return reject()
      }
    }
  }

  return {
    taskList,
    treeProps: props,
    handleLoad
  }
}
